package com.xuzy.x808.server.processor;

import com.xuzy.x808.common.enums.MsgTypeEnum;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ProcessServiceRegister implements ApplicationContextAware, InitializingBean {

    /**
     * 在Spring启动时，将ProcessService的实现者都维护到map中，key是msgId,value是ProcessService的实现类，也就是各个协议的处理器类
     * 构成一个策略模式，方便调用
     */
    private Map<Integer, ProcessService> processorMap = new ConcurrentHashMap<>(16);

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 遍历ProcessService的实现类，维护起来让后面的业务根据msgId来选择对应处理器
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() {
        Map<String, ProcessService> processServiceMap = applicationContext.getBeansOfType(ProcessService.class);
        for (String beanName : processServiceMap.keySet()) {
            if (MsgTypeEnum.getMsgIdByName(beanName) != 0x00) {
                processorMap.put(MsgTypeEnum.getMsgIdByName(beanName), processServiceMap.get(beanName));
            }
        }
    }

    public ProcessService getProcessor(int msgId) {
        return processorMap.get(msgId);
    }
}
